package com.test.Servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownLoadFile extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String filePath = req.getParameter("path");
		String fileName = filePath.substring(filePath.lastIndexOf("\\")+1,filePath.length());
		resp.setContentType("text/x-msdownload");
		resp.addHeader("Content-Disposition", "attachment; filename=\""
				+ fileName + "\"");
		FileInputStream inputStream = new FileInputStream(filePath);
		OutputStream os = resp.getOutputStream();
		byte[] b = new byte[1024];
		int i = 0;
		while ((i = inputStream.read(b)) > 0) {
			os.write(b,0,i);
		}
		inputStream.close();
		os.flush();
		os.close();
	}

}
